﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using CqCore.Extensions;

namespace CqCore.Messaging
{
    public class Message<TEntity> : IMessageTopic
    {
        public Message(TEntity entity)
        {
            Head = new MessageHeader();
            Body = entity;
            Context = new MessageContext();
        }

        [JsonProperty("head")]
        public MessageHeader Head { get; set; }

        [JsonProperty("body")]
        public TEntity Body { get; set; }

        [JsonProperty("context")]
        public MessageContext Context { get; set; }

        /// <summary>
        /// 消息主题，由Category和Type组合而成
        /// 例如：communication.todo.subscription、communication.todo.publish.append等
        /// </summary>
        [JsonProperty("topic")]
        public virtual string Topic => Head.Target.ToTopic();

        public string Serialize()
        {
            return JsonConvert.SerializeObject(this, JsonExtensions.DefaultSettings);
        }

        public static Message<TEntity> Deserialize(string json)
        {
            return JsonConvert.DeserializeObject<Message<TEntity>>(json, JsonExtensions.DefaultSettings);
        }

        public JObject ToJSON()
        {
            return JObject.FromObject(this);
        }
    }
}
